<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="24" :xs="24">
        <!-- 数据筛选表单 -->
        <el-form
          ref="queryForm"
          :model="queryParams"
          :inline="true"
          label-width="100px"
        >
          <!-- 数据筛选表单组件 -->
          <el-form-item label="账号" prop="username">
            <el-input
              v-model="queryParams.username"
              placeholder="请输入账号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input
              v-model="queryParams.nickname"
              placeholder="请输入昵称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <!-- 数据筛选操作按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索
            </el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 数据操作按钮
        <el-row :gutter="20">
          <el-col :span="3">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="handleAdd"
              >新增用户
            </el-button>
          </el-col>
        </el-row> -->

        <!-- 数据表格 -->
        <el-table v-loading="loading" :data="userList">
          <!-- 数据表格列 -->
          <el-table-column label="用户ID" align="center" prop="id" />
          <el-table-column label="账号" align="center" prop="username" />
          <el-table-column label="用户昵称" align="center" prop="nickname" />
          <el-table-column label="邮箱" align="center" prop="email" />
          <el-table-column label="手机号" align="center" prop="phone" />
          <el-table-column label="头像" align="center" prop="headUrl">
            <template slot-scope="scope">
              <el-image :src="scope.row.headUrl" fit="fill" :lazy="true"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="性别" align="center" prop="sex">
            <template slot-scope="scope">
              <span v-if="scope.row.sex === 0">未知</span>

              <span v-else-if="scope.row.sex === 1">男</span>

              <span v-else-if="scope.row.sex === 2">女</span>
            </template>
          </el-table-column>
          <el-table-column label="等级" align="center" prop="level" />

          <!-- 数据行操作按钮 -->
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="small"
                type="text"
                icon="el-icon-key"
                @click="handleRole(scope.row)"
                >分配角色</el-button
              >
              <el-button
                size="small"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                >修改
              </el-button>
              <el-button
                size="small"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 数据分页加载 -->
        <el-pagination
          :current-page="current"
          :page-sizes="[5, 10, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 添加修改user对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 数据编辑表单组件 -->
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="" clearable filterable>
            <el-option
              v-for="item in sexOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="headUrl">
          <!-- <el-image
            :src="form.headUrl"
            fit="fill"
            :lazy="true"
            style="width: 200px"
          ></el-image> -->
          <SingleUpload @modifyAvatar="changeUrl" :value="form.headUrl" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机" />
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-select v-model="form.level" placeholder="" clearable filterable>
            <el-option
              v-for="item in levelOptions"
              :key="item.value"
              :label="item.value"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 数据提交操作按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      :title="roleTitle"
      :visible.sync="roleDialogFormVisible"
      width="300px"
    >
      <el-form :model="roleForm">
        <el-tree
          ref="roleTree"
          :data="roleTreeData"
          show-checkbox
          :check-strictly="checkStrictly"
          node-key="id"
          :default-expand-all="true"
          :props="defaultProps"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAuthRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
/** 导入axios Api */
import {
  listUserByPage,
  getUser,
  addUser,
  updateUser,
  deleteUser,
  authRole,
} from "@/api/user";
import SingleUpload from "@/components/upload/singleUpload";
import { listRoleByPage } from "@/api/role";
export default {
  name: "User",
  components: {
    SingleUpload,
  },
  data() {
    return {
      roleQuery: {
        current: 1,
        id: "",
        pageSize: 100,
        roleDescription: "",
        roleKey: "",
        roleName: "",
        sortField: "create_time",
        sortOrder: "",
      },
      levelOptions: [
        {
          value: 1,
        },
        {
          value: 2,
        },
        {
          value: 3,
        },
        {
          value: 4,
        },
        {
          value: 5,
        },
        {
          value: 6,
        },
      ],
      nickname: "",
      sexOptions: [
        {
          label: "男",
          value: 1,
        },
        {
          label: "女",
          value: 2,
        },
        {
          label: "未知",
          value: 0,
        },
      ],
      // User类型
      typeOptions: undefined,
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 当前页
      current: 0,
      // 每页数据量
      pageSize: 0,
      // User表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 数据查询参数
      queryParams: {
        current: 1,
        email: "",
        id: "",
        level: 0,
        nickname: "",
        pageSize: 10,
        phone: "",
        point: 0,
        sex: 0,
        sortField: "create_time",
        sortOrder: "",
        username: "",
      },
      // 数据编辑表单
      form: {
        id: "",
        username: "",
        nickname: "",
        sex: "",
        email: "",
        headUrl: "",
        level: "",
      },
      // 表单数据校验规则
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        nickname: [
          { required: true, message: "昵称不能为空", trigger: "blur" },
        ],
      },
      roleDialogFormVisible: false,
      defaultProps: {
        label: "roleName",
      },
      roleForm: {},
      roleTreeData: [],
      checkStrictly: true,
      roleTitle: "",
    };
  },
  created() {
    this.getList();
  },
  methods: {
    changeUrl(headUrl) {
      this.form.headUrl = headUrl;
    },
    /** 查询User数据列表 */
    getList() {
      this.loading = true;
      listUserByPage(this.queryParams).then((response) => {
        this.userList = response.data.records;
        this.total = response.data.total;
        this.current = this.queryParams.current;
        this.pageSize = this.queryParams.pageSize;
        this.loading = false;
      });
    },
    /** 处理分页 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getList();
    },

    /** 数据编辑对话框取消按钮 */
    cancel() {
      this.open = false;
      this.resetForm();
    },

    /** 数据编辑表单清空 */
    resetForm() {
      this.form = {
        id: null,
        username: null,
        nickname: null,
      };
    },

    resetRoleForm() {
      this.roleForm = {
        userId: null,
        roleIds: [],
      };
    },

    /** 数据筛选参数重置按钮 */
    resetQueryParams() {
      this.queryParams.current = 1;
      this.queryParams.pageSize = 5;
    },

    /** 数据筛选搜索按钮 */
    handleQuery() {
      this.resetQueryParams();
      this.getList();
      this.$message.success("查询成功");
    },

    /** 数据筛选重置按钮 */
    resetQuery() {
      this.queryParams = {
        current: 1,
        email: "",
        id: "",
        level: 0,
        nickname: "",
        pageSize: 10,
        phone: "",
        point: 0,
        sex: 0,
        sortField: "create_time",
        sortOrder: "",
        username: "",
      };
      this.getList();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.resetForm();
      this.open = true;
      this.title = "添加User";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetForm();
      getUser(row.id).then((response) => {
        if (response.code == 200) {
          let data = response.data;
          this.form = data;
          this.nickname = data.nickname;
          this.open = true;
          this.title = "修改用户";
        }
      });
    },

    /** 数据提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id === null) {
            addUser(this.form).then((response) => {
              this.$message.success(response.msg);
              this.open = false;
              this.title = "";
              this.getList();
            });
          } else {
            let tem = JSON.parse(JSON.stringify(this.form));
            if (tem.nickname != this.nickname) {
              this.form = {
                id: tem.id,
                nickname: tem.nickname,
                username: tem.username,
                headUrl: tem.headUrl,
                sex: tem.sex,
                phone: tem.phone,
                level: tem.level,
                email: tem.email,
              };
            } else {
              this.form = {
                id: tem.id,
                username: tem.username,
                headUrl: tem.headUrl,
                sex: tem.sex,
                phone: tem.phone,
                level: tem.level,
                email: tem.email,
              };
            }

            updateUser(this.form).then((response) => {
              if (response.code == 200) {
                this.open = false;
                this.title = "";
                this.getList();
                this.$message.success("修改成功");
              }
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(
        '是否确认删除名称为"' + row.username + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return deleteUser({ id: row.id });
        })
        .then(() => {
          this.getList();
          this.$message.success("删除成功");
        })
        .catch(() => {});
    },

    /** 处理分配角色 */
    handleRole(row) {
      this.roleForm.userId = row.id;
      this.roleTitle = "为用户[" + row.nickname + "]分配角色";
      this.roleDialogFormVisible = true;
      listRoleByPage(this.roleQuery).then((response) => {
        this.roleTreeData = response.data.records;
      });
      getUser(this.roleForm.userId).then((response) => {
        var roles = response.data.userRoleVo.roleList;
        if (roles) {
          const roleIds = roles.map((item) => item.id);
          this.$refs.roleTree.setCheckedKeys(roleIds);
        } else {
          this.$refs.roleTree.setCheckedKeys([]);
        }
      });
    },
    /** 提交分配角色表单 */
    submitAuthRole() {
      let roleIds = [... this.$refs.roleTree.getCheckedKeys()]
      console.log(roleIds);
      this.roleForm.roleIds = roleIds
      authRole(this.roleForm).then((response) => {
        this.$message.success("分配成功");
        this.roleDialogFormVisible = false;
        this.resetRoleForm();
      });
    },
  },
};
</script>
  